import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginView from "@/views/LoginView.vue";
import AdminView from "@/views/AdminView.vue";
import store from '../store'
import ElementUI from 'element-ui';
import Index from "@/views/Index.vue";
import UserView from "@/views/UserView.vue";
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:'/login'
  },
  {
    path:'/login',
    name:'login',
    component: LoginView
  },
  {
    path: '/admin',
    name: 'admin',
    component: AdminView,
    children:[
      {
        path:'',
        name: 'index',
        component: Index
      },
      {
        path:'user',
        name: 'user',
        component: UserView
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 定义路由守卫
router.beforeEach((to,from,next)=>{
  console.log("to",to)
  if (to.path === '/login') { // 去登录,直接放行
    next()
  } else { // 其他页面,需要登录后的身份信息
    // 取出信息
    if(!store.state.user) {
      ElementUI.Message.error("没有用户信息,禁止访问!")
      next({path:'/login'})
    } else {
      next()
    }
  }
})

export default router
